/*
 * WeightParser.java
 *
 * Copyright (C) 2014 Fabian Wenzelmann
 *
 * This file is part of stura_voting.
 *
 * stura_voting is free software: you
 * can redistribute it and/or modify it under the terms of the
 * GNU General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * stura_voting is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
 * Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with stura_voting.
 *
 * If not, see <http://www.gnu.org/licenses/>.
 */
 
package de.stura;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.IOException;
 
/**
 * Parses weighted votes from a text file / any BufferedReader object.
 * 
 * The syntax of the input is very easy: Each line consists of a name followed by
 * a tab followed by the weight (an integer).
 */
public class WeightParser {
    
    public WeightParser() { }
    
    /**
     * Parses the input and returns all voters in an ArrayList.
     * 
     * The syntax is as follows:
     * <NAME><TAB><WEIGHT>
     * where WEIGHT must be the representation of an integer.
     * 
     * All lines starting with # will be ignored as a comment line.
     * 
     * @param br The reader to read from.
     * @throws IOException If a reading error occurs.
     * @throws WeightFormatException If the format of the input has invalid syntax.
     */
    public ArrayList<WeightedVoter> parseWeights(BufferedReader br) throws IOException, WeightFormatException {
        String line;
        ArrayList<WeightedVoter> result = new ArrayList<WeightedVoter>();
        int lineNum = 0;
        while ((line = br.readLine()) != null) {
            ++lineNum;
            if (line.startsWith("#")) {
                continue;
            }
            String[] split = line.split("\t");
            if (split.length != 2) {
                throw new WeightFormatException(lineNum, line, "Line doesn't contain a '\\t'");
            }
            String voter = split[0];
            int weight = -1;
            try {
                weight = Integer.parseInt(split[1]);
            } catch (NumberFormatException e) {
                throw new WeightFormatException(lineNum, line, "Cannot parse second value as integer", e);
            }
            result.add(new WeightedVoter(voter, weight));
        }
        return result;
    }
    
    public HashMap<String, WeightedVoter> mapFromList(ArrayList<WeightedVoter> lst) {
        HashMap<String, WeightedVoter> res = new HashMap<String, WeightedVoter>();
        
        for (WeightedVoter v : lst) {
            res.put(v.getVoter(), v);
        }
        
        return res;
    }
    
}
